package com.adkun.community.controller.interceptor;

import com.adkun.community.entity.LoginTicket;
import com.adkun.community.entity.User;
import com.adkun.community.service.UserService;
import com.adkun.community.util.CookieUtil;
import com.adkun.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.Authenticator;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    HostHolder hostHolder;

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 通过Cookie得到Ticket
        String ticket = CookieUtil.getCookieValueFromRequest(request, "ticket");

        if (ticket != null) {
            // 获取凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 如果查询结果不为空 && 状态为0（有效） && 并且过期时间比现在要晚
                User u = userService.findUserById(loginTicket.getUserId());
                // 在本次请求中持有用户（存入内存）
                // 让多线程并发可以请求该用户对象
                hostHolder.setUser(u);
                // 构建用户认证的结果，并存入SecurityContxt，以便于Security进行授权。
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        u,
                        u.getPassword(),
                        userService.getAuthorities(u.getId())
                );
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User u = hostHolder.getUser();
        if (u != null && modelAndView != null) {
            modelAndView.addObject("loginUser", u);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
        // 清理掉SecurityContext
//        SecurityContextHolder.clearContext();
    }
}
